package StudentSystem;

import java.io.*;
import java.util.Scanner;

class Student {
    String id;
    String name;
    int mathScore;
    int chineseScore;
    int englishScore;
    Student prev;
    Student next;

    public Student(String id, String name, int mathScore, int chineseScore, int englishScore) {
        this.id = id;
        this.name = name;
        this.mathScore = mathScore;
        this.chineseScore = chineseScore;
        this.englishScore = englishScore;
        this.prev = null;
        this.next = null;
    }

    public int getTotalScore() {
        return mathScore + chineseScore + englishScore;
    }

    @Override
    public String toString() {
        return String.format("学号: %s, 姓名: %s, 数学: %d, 语文: %d, 英语: %d, 总分: %d",
                id, name, mathScore, chineseScore, englishScore, getTotalScore());
    }
}

public class StudentManagementSystem {
    private Student head;
    private Student tail;
    private int size;
    private Scanner scanner;

    public StudentManagementSystem() {
        head = null;
        tail = null;
        size = 0;
        scanner = new Scanner(System.in);
    }

    // 插入学生信息
    public void insertStudent() {
        System.out.println("开始输入学生信息，输入0000时结束。");
        while (true) {
            System.out.print("请输入学生的学号：");
            String id = scanner.next();
            if (id.equals("0000")) {
                System.out.println("保存成功！");
                break;
            }

            System.out.print("请输入学生的姓名：");
            String name = scanner.next();
            System.out.print("请输入学生的数学成绩：");
            int mathScore = scanner.nextInt();
            System.out.print("请输入学生的语文成绩：");
            int chineseScore = scanner.nextInt();
            System.out.print("请输入学生的英语成绩：");
            int englishScore = scanner.nextInt();

            Student newStudent = new Student(id, name, mathScore, chineseScore, englishScore);
            addToEnd(newStudent);
        }
    }

    private void addToEnd(Student student) {
        if (head == null) {
            head = student;
            tail = student;
        } else {
            tail.next = student;
            student.prev = tail;
            tail = student;
        }
        size++;
    }

    // 删除学生信息
    public void deleteStudent() {
        System.out.print("请输入要删除的学生学号：");
        String id = scanner.next();
        Student current = head;

        while (current != null) {
            if (current.id.equals(id)) {
                if (current.prev != null) {
                    current.prev.next = current.next;
                } else {
                    head = current.next;
                }

                if (current.next != null) {
                    current.next.prev = current.prev;
                } else {
                    tail = current.prev;
                }

                size--;
                System.out.println("删除成功！");
                return;
            }
            current = current.next;
        }
        System.out.println("未找到该学号的学生！");
    }

    // 修改学生成绩
    public void modifyStudent() {
        System.out.print("请输入要修改的学生学号：");
        String id = scanner.next();
        Student current = head;

        while (current != null) {
            if (current.id.equals(id)) {
                System.out.print("请输入新的数学成绩：");
                current.mathScore = scanner.nextInt();
                System.out.print("请输入新的语文成绩：");
                current.chineseScore = scanner.nextInt();
                System.out.print("请输入新的英语成绩：");
                current.englishScore = scanner.nextInt();
                System.out.println("修改成功！");
                return;
            }
            current = current.next;
        }
        System.out.println("未找到该学号的学生！");
    }

    // 查找学生信息
    public void searchStudent() {
        System.out.print("请输入要查找的学生学号：");
        String id = scanner.next();
        Student current = head;

        while (current != null) {
            if (current.id.equals(id)) {
                System.out.println(current);
                return;
            }
            current = current.next;
        }
        System.out.println("未找到该学号的学生！");
    }

    // 学生成绩排序（按总分降序）
    public void sortStudents() {
        if (head == null || head.next == null) {
            return;
        }

        boolean swapped;
        do {
            swapped = false;
            Student current = head;
            while (current.next != null) {
                if (current.getTotalScore() < current.next.getTotalScore()) {
                    swapNodes(current, current.next);
                    swapped = true;
                }
                current = current.next;
            }
        } while (swapped);

        System.out.println("排序完成！");
    }

    private void swapNodes(Student a, Student b) {
        // 交换数据而不是节点指针，简化操作
        String tempId = a.id;
        String tempName = a.name;
        int tempMath = a.mathScore;
        int tempChinese = a.chineseScore;
        int tempEnglish = a.englishScore;

        a.id = b.id;
        a.name = b.name;
        a.mathScore = b.mathScore;
        a.chineseScore = b.chineseScore;
        a.englishScore = b.englishScore;

        b.id = tempId;
        b.name = tempName;
        b.mathScore = tempMath;
        b.chineseScore = tempChinese;
        b.englishScore = tempEnglish;
    }

    // 显示所有学生信息
    public void displayAllStudents() {
        if (head == null) {
            System.out.println("没有学生信息！");
            return;
        }

        Student current = head;
        while (current != null) {
            System.out.println(current);
            current = current.next;
        }
    }

    // 保存数据到文件
    public void saveData() {
        try (PrintWriter writer = new PrintWriter(new FileWriter("students.txt"))) {
            Student current = head;
            while (current != null) {
                writer.println(current.id + "," + current.name + "," +
                        current.mathScore + "," + current.chineseScore + "," +
                        current.englishScore);
                current = current.next;
            }
            System.out.println("数据保存成功！");
        } catch (IOException e) {
            System.out.println("保存数据时出错：" + e.getMessage());
        }
    }

    // 从文件读取数据
    public void loadData() {
        try (BufferedReader reader = new BufferedReader(new FileReader("students.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 5) {
                    Student student = new Student(
                            parts[0], parts[1],
                            Integer.parseInt(parts[2]),
                            Integer.parseInt(parts[3]),
                            Integer.parseInt(parts[4]));
                    addToEnd(student);
                }
            }
            System.out.println("数据加载成功！");
        } catch (IOException e) {
            System.out.println("读取数据时出错：" + e.getMessage());
        }
    }

    // 显示菜单
    public void showMenu() {
        System.out.println("\n学生信息管理系统");
        System.out.println("1. 插入学生信息");
        System.out.println("2. 删除学生信息");
        System.out.println("3. 修改学生成绩");
        System.out.println("4. 查找学生信息");
        System.out.println("5. 显示所有学生信息");
        System.out.println("6. 学生成绩排序");
        System.out.println("7. 保存数据");
        System.out.println("8. 读取数据");
        System.out.println("9. 退出系统");
        System.out.print("请选择操作：");
    }

    public static void main(String[] args) {
        StudentManagementSystem system = new StudentManagementSystem();
        Scanner scanner = new Scanner(System.in);
        int choice;

        do {
            system.showMenu();
            choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    system.insertStudent();
                    break;
                case 2:
                    system.deleteStudent();
                    break;
                case 3:
                    system.modifyStudent();
                    break;
                case 4:
                    system.searchStudent();
                    break;
                case 5:
                    system.displayAllStudents();
                    break;
                case 6:
                    system.sortStudents();
                    system.displayAllStudents();
                    break;
                case 7:
                    system.saveData();
                    break;
                case 8:
                    system.loadData();
                    break;
                case 9:
                    System.out.println("感谢使用，再见！");
                    break;
                default:
                    System.out.println("无效的选择，请重新输入！");
            }
        } while (choice != 9);
    }
}